﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PowerView.Page
{
    public partial class MainForm : Form
    {
        Wave_Form wave_Form;
        PD_Form pd_Form;
        UFCS_Form ufcs_Form;
        QC_Form qc_Form;
        AFC_Form afc_Form;

        Form curr_Form;
        Button curr_Btn;

        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
            KeyPreview = true;
            wave_Form = new Wave_Form();
            pd_Form = new PD_Form();
            ufcs_Form = new UFCS_Form();
            qc_Form = new QC_Form();
            afc_Form = new AFC_Form();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Resfresh_COM();
            MiddleWare.default_color = PD_Form_Btn.BackColor;

            wave_Form.TopLevel = false;
            wave_Form.Parent = wave_panel;
            wave_Form.Show();

            pd_Form.TopLevel = false;
            pd_Form.Parent = protocol_panel;

            ufcs_Form.TopLevel = false;
            ufcs_Form.Parent = protocol_panel;

            qc_Form.TopLevel = false;
            qc_Form.Parent = protocol_panel;

            afc_Form.TopLevel = false;
            afc_Form.Parent = protocol_panel;

            pd_Form.Show();
            curr_Form = pd_Form;
            curr_Btn = PD_Form_Btn;
            PD_Form_Btn.BackColor = Color.LightGreen;

            Addr_cBox.SelectedIndex = 0;

            MiddleWare.log_tBox = Log_tBox;
            MiddleWare.com_cBox = COM_cBox;

            MiddleWare.recv_thread.IsBackground = true;
            MiddleWare.recv_thread.Start();
        }

        private void Resfresh_COM()
        { 
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity where Name like '%(COM%'");
            COM_cBox.Items.Clear();
            var hardInfos = searcher.Get();
            foreach (var hardInfo in hardInfos)
            {
                if (hardInfo.Properties["Name"].Value != null)
                {
                    string deviceName = hardInfo.Properties["Name"].Value.ToString();
                    COM_cBox.Items.Add(deviceName);
                }
            }
            if (COM_cBox.Items.Count > 0) COM_cBox.SelectedIndex = 0;
            else COM_cBox.Text = "未发现串口设备";
        }

        private void button10_Click(object sender, EventArgs e)
        {

        }

        private void Refresh_COM_Btn_Click(object sender, EventArgs e)
        {
            Resfresh_COM();
        }

        private void Open_COM_Btn_Click(object sender, EventArgs e)
        {
            if (Open_COM_Btn.Text == "关闭串口")
            {
                try
                {
                    MiddleWare.serial_port.Close();
                }
                catch (Exception){ }
                Open_COM_Btn.Text = "打开串口";
                COM_cBox.BackColor = Color.White;
                wave_Form.Wave_Stop();
                return;
            }
            string deviceName = COM_cBox.Text;
            int startIndex = deviceName.IndexOf("(");
            int endIndex = deviceName.IndexOf(")");
            if (startIndex < 0 || startIndex < 0 || startIndex > endIndex)
            {
                COM_cBox.BackColor = Color.Pink;
                return;
            }
            string SerialName = deviceName.Substring(startIndex + 1, endIndex - startIndex - 1);
            if (!SerialName.StartsWith("COM"))
            {
                COM_cBox.BackColor = Color.Pink;
                return;
            }

            try
            {
                MiddleWare.serial_port = new System.IO.Ports.SerialPort();
                MiddleWare.serial_port.PortName = SerialName;
                MiddleWare.serial_port.BaudRate = 1000000;
                MiddleWare.serial_port.ReadBufferSize = 2048;
                MiddleWare.serial_port.ReadTimeout = 100;
                MiddleWare.serial_port.ReceivedBytesThreshold = 5;
                MiddleWare.serial_port.Open();
            }
            catch
            {
                COM_cBox.BackColor = Color.Pink;
                Log_tBox.AppendText("打开串口失败!!");
                return;
            }
            Open_COM_Btn.Text = "关闭串口";
            COM_cBox.BackColor = Color.LightGreen;
            Log_tBox.AppendText("打开串口成功!!\r\n");
            wave_Form.Wave_Run();
        }

        private void Swap_Form(Button new_Btn, Form new_Form)
        {
            if (new_Btn == curr_Btn)
            {
                return;
            }
            curr_Form.Hide();
            new_Form.Show();

            curr_Btn.BackColor = MiddleWare.default_color;
            new_Btn.BackColor = Color.LightGreen;

            curr_Form = new_Form;
            curr_Btn = new_Btn;
        }

        private void PD_Form_Btn_Click(object sender, EventArgs e)
        {
            Swap_Form(PD_Form_Btn, pd_Form);
        }

        private void UFCS_Form_Btn_Click(object sender, EventArgs e)
        {
            Swap_Form(UFCS_Form_Btn, ufcs_Form);
        }

        private void QC_Form_Btn_Click(object sender, EventArgs e)
        {
            Swap_Form(QC_Form_Btn, qc_Form);
        }

        private void AFC_Form_Btn_Click(object sender, EventArgs e)
        {
            Swap_Form(AFC_Form_Btn,afc_Form);
        }

        private void wave_panel_SizeChanged(object sender, EventArgs e)
        {
            wave_Form.Width = wave_panel.Width;
            wave_Form.Height = wave_panel.Height;
        }

        public void MainForm_CMD_Proc(byte[] cmd)
        {
            switch (cmd[3])
            {
                case 0x00:
                    Version_textBox.Text = "PowerV_G4, V"+cmd[6].ToString() + "." + cmd[7].ToString()+", Addr:" + cmd[8].ToString("X2");
                    break;
                default:
                    break;

            }
        }


        private void CMD_Proc_timer_Tick(object sender, EventArgs e)
        {
            while (MiddleWare.CMD_Queue.Count > 0)
            {
                byte[] cmd = (byte[])MiddleWare.CMD_Queue.Dequeue();

                switch(cmd[2] & 0xF0)
                {
                    case 0x00:
                        MainForm_CMD_Proc(cmd);
                        break;
                    case 0x10:
                        pd_Form.CMD_Proc(cmd);
                        break;
                    case 0x20:
                        ufcs_Form.CMD_Proc(cmd);
                        break;
                    case 0x30:
                        qc_Form.CMD_Proc(cmd);
                        break;
                    case 0x40:
                        afc_Form.CMD_Proc(cmd);
                        break;
                }
            }
        }

        private void info_linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("https://gitee.com/ospanic/PowerView");
        }

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F12) 
            {
                wave_Form.Run_Btn_Click(null, null);
            }
        }

        private void Clear_Log_Btn_Click(object sender, EventArgs e)
        {
            Log_tBox.Clear();
            Tx_Label.Text = "Tx:0";
            Rx_Lable.Text = "Rx:0";
        }

        private void Get_Device_Info_Btn_Click(object sender, EventArgs e)
        {
            MiddleWare.Write_CMD(0xFF, 0x00, 0x00, null, 0);
        }

        private void Set_Addr_Btn_Click(object sender, EventArgs e)
        {
            byte addr = Convert.ToByte(Addr_cBox.Text.Substring(2,2), 16);
            MiddleWare.Write_CMD(0xFF, 0x00, 0x3, new byte[1] { addr }, 1);
        }
    }
}
